package com.controller;

import com.entity.CommonAttachment;
import com.service.AttachmentService;
import com.utils.MyFileUtils;
import com.vo.UploadResult;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@ConfigurationProperties("file")
@RequestMapping("/attachment")
public class AttachmentController {
    @Value("${path}")
    private String path;
    @Autowired
    AttachmentService AttachmentService;
//传整文件的md5用于秒传，分片的md5用于保证不丢包，额外的uuid用于合并文件，
//    不能用整体文件md5，防止2个人同时传一个文件 
    @PostMapping("/partUpload")
    public UploadResult bigFile(HttpServletRequest request, HttpServletResponse response, String guid, Integer chunk, MultipartFile file, String fileName, Integer chunks) {
        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                if (chunk == null)
                    chunk = 0;
                // 临时目录用来存放所有分片文件
                String tempFileDir = path + guid;
                File parentFileDir = new File(tempFileDir);
                if (!parentFileDir.exists()) {
                    parentFileDir.mkdirs();
                }
                // 分片处理时，前台会多次调用上传接口，每次都会上传文件的一部分到后台
                File tempPartFile = new File(parentFileDir, guid + "_" + chunk + ".part");
                FileUtils.copyInputStreamToFile(file.getInputStream(), tempPartFile);
            }
        } catch (Exception e) {
            return UploadResult.failMessage(400, e.getMessage());
        }
        if (chunk + 1 == chunks) {
            mergeFile(guid, fileName);
        }
        return UploadResult.successMessage(200, "上次成功");
    }

    @RequestMapping("merge")
    public UploadResult mergeFile(String guid, String fileName) {
        // 得到 destTempFile 就是最终的文件
        try {
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
            //时间格式化格式
            Date currentTime = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
            //拼接新的文件名
            String newName = UUID.randomUUID().toString().replace("-", "");
            String tmp = simpleDateFormat.format(currentTime);
            File parentFileDir = new File(path + guid);
            if (parentFileDir.isDirectory()) {
                File destTempFile = new File(path + tmp, newName);
                if (!destTempFile.exists()) {
                    //先得到文件的上级目录，并创建上级目录，在创建文件
                    destTempFile.getParentFile().mkdir();
                    try {
                        destTempFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                long length = 0;
                for (int i = 0; i < parentFileDir.listFiles().length; i++) {
                    File partFile = new File(parentFileDir, guid + "_" + i + ".part");
                    length += partFile.length();
                    FileOutputStream destTempfos = new FileOutputStream(destTempFile, true);
                    //遍历"所有分片文件"到"最终文件"中
                    FileUtils.copyFile(partFile, destTempfos);
                    destTempfos.close();
                }
//                文件大小
                String fileSize = MyFileUtils.getFileSize(length);
                // 删除临时目录中的分片文件
                FileUtils.deleteDirectory(parentFileDir);
                CommonAttachment attachment = new CommonAttachment();
                attachment.setId(newName);
                attachment.setFileSize(fileSize);
                attachment.setBusinessId("8dda90c3fe56442aa98e2de8565627e8");
                attachment.setBusinessTableName("BBBBB");
                attachment.setSuffix(fileSuffix);
                attachment.setFilePath(path + tmp+"//"+newName);
                attachment.setFileName(fileName.substring(0,fileName.lastIndexOf(".")));
                int result = AttachmentService.insertSelective(attachment);
                if (result>0) {
                    System.out.println("上传成功");
                }
                return UploadResult.successMessage(200, "合并成功");
            } else {
                return UploadResult.failMessage(400, "没找到目录");
            }
        } catch (Exception e) {
            return UploadResult.failMessage(400, e.getMessage());
        }
    }
    
    
    /*下载，支持预览*/
    @RequestMapping("/downLoad")
    public void downLoad(String filePath, HttpServletResponse response,HttpServletRequest request, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
//        response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com"); 
//        response.setHeader("Access-Control-Allow-Origin","*");
//        response.setContentType("text/json; charset=utf-8");
//        response.setHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS,DELETE");
//        response.setHeader("Access-Control-Max-Age","3600");
//        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//        String callback=request.getParameter("callback");
//        if(null==callback){
//          System.out.println("不是跨域请求");
//        }else{
//          System.out.println("是跨域请求");
//        }
       
        response.reset(); // 非常重要
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }
    
    
    
    
    @RequestMapping("queryFiles")
    public List<CommonAttachment>  queryFiles(@RequestBody CommonAttachment commonAttachment) {
        List<CommonAttachment>  commonAttachmentList = AttachmentService.selectByTableNameAndBusinessId(commonAttachment);
       for (CommonAttachment commonAttachmentVo : commonAttachmentList) {
           commonAttachmentVo.setFileName(commonAttachmentVo.getFileName()+commonAttachmentVo.getSuffix());
           }
        return commonAttachmentList;
    }
    @RequestMapping("delFileByIds")
    public int  delFileByIds(@RequestBody Map<String, Object> idMap) {
        Object idList = idMap.get("id");
        List<String> ids = Arrays.stream(idList.toString().split(",")).collect(Collectors.toList());
        int result= AttachmentService.delAttachments(ids);
        return result;
    }
}